import json

from django.http import HttpResponse
from django.shortcuts import render
import os
import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "green.settings")
django.setup()

# render请求
from green import models


def four(request):
    return render(request, "four/four.html")


def initFour(request):
    myjson = {}
    yearList = ['number_2017green', 'number_2018green', 'number_2019green']
    for oneyear in yearList:
        tempList = []
        queryData = models.Citygreen.objects.values('city', oneyear)
        print(queryData)
        for cityInfo in queryData:
            if cityInfo[oneyear] is None:
                continue
            else:
                tempList.append({'city': cityInfo['city'].split()[0], 'num': float(cityInfo[oneyear])})
        tempList.sort(key=lambda stu: stu["num"], reverse=True)
        myjson[oneyear[7:11]] = tempList
    print(myjson)
    # print("json里面的数据")
    # print(myjson)
    # 将json保存为文件
    s = json.dumps(myjson)
    f = open('../../templates/four/showFour.json', 'w', encoding='UTF-8')
    f.write(s)
    f.close()
    print('构造成功')
    return HttpResponse("构造成功！")


def showFour(request):
    year = str(request.GET.get('year'))
    f = open('templates/four/showFour.json', 'r', encoding='utf-8')
    data = f.read()
    data = json.loads(data)[year]
    data = {"data": data}
    print(data)
    f.close()

    # person_str = json.dumps(person)
    # response = HttpResponse(person_str , content_type='application/json; charset=utf-8')
    response = HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8')
    return response


if __name__ == '__main__':
    initFour(0)
